<?php 
include 'includes/header.php';
require_once 'config/database.php';

$database = new Database();
$db = $database->getConnection();

// Get filters from URL
$brand_id = $_GET['brand'] ?? null;
$min_price = $_GET['min_price'] ?? null;
$max_price = $_GET['max_price'] ?? null;
$body_type = $_GET['body_type'] ?? null;
$fuel_type = $_GET['fuel_type'] ?? null;
$search = $_GET['search'] ?? null;

// Build query conditions
$where = ['c.status = "Available"'];
$params = [];

if ($brand_id) {
    $where[] = "c.brand_id = :brand_id";
    $params[':brand_id'] = $brand_id;
}
if ($min_price) {
    $where[] = "c.price >= :min_price";
    $params[':min_price'] = $min_price;
}
if ($max_price) {
    $where[] = "c.price <= :max_price";
    $params[':max_price'] = $max_price;
}
if ($body_type) {
    $where[] = "c.body_type = :body_type";
    $params[':body_type'] = $body_type;
}
if ($fuel_type) {
    $where[] = "c.fuel_type = :fuel_type";
    $params[':fuel_type'] = $fuel_type;
}
if ($search) {
    $where[] = "(c.title LIKE :search OR b.name LIKE :search OR m.name LIKE :search)";
    $params[':search'] = "%$search%";
}

$where_clause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 8;
$offset = ($page - 1) * $per_page;

// Get total cars
$count_query = "SELECT COUNT(*) FROM cars c 
                LEFT JOIN brands b ON c.brand_id = b.id 
                LEFT JOIN models m ON c.model_id = m.id 
                $where_clause";
$count_stmt = $db->prepare($count_query);
foreach ($params as $key => $value) {
    $count_stmt->bindValue($key, $value);
}
$count_stmt->execute();
$total_cars = $count_stmt->fetchColumn();
$total_pages = ceil($total_cars / $per_page);

// Get cars
$query = "SELECT c.*, b.name as brand_name, m.name as model_name 
          FROM cars c 
          LEFT JOIN brands b ON c.brand_id = b.id 
          LEFT JOIN models m ON c.model_id = m.id 
          $where_clause 
          ORDER BY c.created_at DESC 
          LIMIT :offset, :per_page";
$stmt = $db->prepare($query);

// Bind parameters
foreach ($params as $key => $value) {
    $stmt->bindValue($key, $value);
}

// Bind the LIMIT parameters
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':per_page', $per_page, PDO::PARAM_INT);

$stmt->execute();
$cars = $stmt->fetchAll();

// Get all brands with car counts
$brands_query = "SELECT b.*, COUNT(c.id) as car_count 
                 FROM brands b 
                 LEFT JOIN cars c ON b.id = c.brand_id AND c.status = 'Available'
                 GROUP BY b.id 
                 ORDER BY b.name";
$brands = $db->query($brands_query)->fetchAll();

// Get price ranges
$price_ranges = [
    ['min' => 0, 'max' => 10000, 'label' => 'Under $10,000'],
    ['min' => 10000, 'max' => 20000, 'label' => '$10,000 - $20,000'],
    ['min' => 20000, 'max' => 30000, 'label' => '$20,000 - $30,000'],
    ['min' => 30000, 'max' => 50000, 'label' => '$30,000 - $50,000'],
    ['min' => 50000, 'max' => null, 'label' => 'Over $50,000']
];

// Get user favorites
$user_favorites = [];
if (isset($_SESSION['user_id'])) {
    $favorites_query = "SELECT car_id FROM favorites WHERE user_id = ?";
    $favorites_stmt = $db->prepare($favorites_query);
    $favorites_stmt->execute([$_SESSION['user_id']]);
    $user_favorites = array_column($favorites_stmt->fetchAll(), 'car_id');
}
?>

<div class="container-fluid py-4">
    <div class="row">
        <!-- Sidebar Filters -->
        <div class="col-lg-3 sidebar-filters">
            <button class="btn btn-primary d-lg-none w-100 mb-3" type="button" data-bs-toggle="offcanvas" data-bs-target="#filtersSidebar">
                <i class="fas fa-filter me-2"></i>Show Filters
            </button>
            
            <!-- Mobile Sidebar -->
            <div class="offcanvas offcanvas-start" tabindex="-1" id="filtersSidebar">
                <div class="offcanvas-header">
                    <h5 class="offcanvas-title">Filters</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
                </div>
                <div class="offcanvas-body">
                    <?php include 'includes/car_filters.php'; ?>
                </div>
            </div>
            
            <!-- Desktop Sidebar -->
            <div class="d-none d-lg-block">
                <?php include 'includes/car_filters.php'; ?>
            </div>
        </div>

        <!-- Main Content -->
        <div class="col-lg-9 ps-lg-4">
            <!-- Advanced Search Collapse -->
            <div class="card shadow-sm mb-4">
                <div class="card-body">
                    <button class="btn btn-outline-primary w-100" type="button" 
                            data-bs-toggle="collapse" data-bs-target="#advancedSearch">
                        <i class="fas fa-search me-2"></i>Advanced Search
                    </button>
                    
                    <div class="collapse mt-3" id="advancedSearch">
                        <form action="" method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">Brand</label>
                                <select name="brand" class="form-select" id="brandSelect">
                                    <option value="">All Brands</option>
                                    <?php foreach ($brands as $brand): ?>
                                        <option value="<?php echo $brand['id']; ?>" 
                                                <?php echo $brand_id == $brand['id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($brand['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-4">
                                <label class="form-label">Model</label>
                                <select name="model" class="form-select" id="modelSelect" disabled>
                                    <option value="">Select Brand First</option>
                                </select>
                            </div>
                            
                            <div class="col-md-3">
                                <label class="form-label">Min Year</label>
                                <select name="min_year" class="form-select">
                                    <option value="">Any</option>
                                    <?php for($y = date('Y'); $y >= 1990; $y--): ?>
                                        <option value="<?php echo $y; ?>"><?php echo $y; ?></option>
                                    <?php endfor; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Max Year</label>
                                <select name="max_year" class="form-select">
                                    <option value="">Any</option>
                                    <?php for($y = date('Y'); $y >= 1990; $y--): ?>
                                        <option value="<?php echo $y; ?>"><?php echo $y; ?></option>
                                    <?php endfor; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-3">
                                <label class="form-label">Min Mileage</label>
                                <input type="number" name="min_mileage" class="form-control" placeholder="0">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Max Mileage</label>
                                <input type="number" name="max_mileage" class="form-control" placeholder="Any">
                            </div>
                            
                            <div class="col-md-3">
                                <label class="form-label">Min Engine (cc)</label>
                                <input type="number" name="min_cc" class="form-control" placeholder="0">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Max Engine (cc)</label>
                                <input type="number" name="max_cc" class="form-control" placeholder="Any">
                            </div>
                            
                            <div class="col-md-3">
                                <label class="form-label">Min Price</label>
                                <input type="number" name="min_price" class="form-control" placeholder="0">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Max Price</label>
                                <input type="number" name="max_price" class="form-control" placeholder="Any">
                            </div>
                            
                            <div class="col-md-3">
                                <label class="form-label">Steering</label>
                                <select name="steering" class="form-select">
                                    <option value="">Any</option>
                                    <option value="Left">Left Hand Drive</option>
                                    <option value="Right">Right Hand Drive</option>
                                </select>
                            </div>
                            
                            <div class="col-12">
                                <button type="submit" class="btn btn-primary">Search Cars</button>
                                <button type="reset" class="btn btn-outline-secondary">Reset</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Cars Grid -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h4>Available Cars (<?php echo $total_cars; ?>)</h4>
                <div class="dropdown">
                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        Sort By
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="?sort=price_asc">Price: Low to High</a></li>
                        <li><a class="dropdown-item" href="?sort=price_desc">Price: High to Low</a></li>
                        <li><a class="dropdown-item" href="?sort=year_desc">Newest First</a></li>
                    </ul>
                </div>
            </div>

            <div class="row row-cols-1 row-cols-md-2 row-cols-lg-4 g-4">
                <?php if (empty($cars)): ?>
                    <div class="col-12">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            No cars available in this category. Please try different filters.
                        </div>
                    </div>
                <?php else: ?>
                    <?php foreach ($cars as $car): ?>
                        <div class="col">
                            <div class="car-card h-100" style="box-shadow: 0px -1px 20px 8px #00000014;">
                                <div class="car-image position-relative">
                                    <?php if (isset($_SESSION['user_id'])): ?>
                                        <button class="btn btn-favorite position-absolute top-0 start-0 m-2 toggle-favorite" 
                                                data-car-id="<?php echo $car['id']; ?>">
                                            <i class="<?php echo in_array($car['id'], $user_favorites) ? 'fas' : 'far'; ?> fa-heart text-success"></i>
                                        </button>
                                    <?php endif; ?>
                                    
                                    <img src="<?php echo htmlspecialchars($car['main_image']); ?>" 
                                         alt="<?php echo htmlspecialchars($car['title']); ?>"
                                         class="img-fluid w-100"
                                         style="height: 200px; object-fit: cover;">
                                    <div class="car-badges position-absolute top-0 end-0 m-2">
                                        <?php if ($car['condition_type'] == 'New'): ?>
                                            <span class="badge bg-success rounded-pill px-3">New</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <h5 class="car-title"><?php echo htmlspecialchars($car['title']); ?></h5>
                                    <div class="car-info">
                                        <span><i class="fas fa-calendar" style="margin-right: 4px;"></i> <?php echo $car['year']; ?></span>
                                        <span><i class="fas fa-road" style="margin-right: 4px;"></i> <?php echo number_format($car['mileage']); ?> km</span>
                                        <span><i class="fas fa-gas-pump" style="margin-right: 4px;"></i> <?php echo $car['fuel_type']; ?></span>
                                    </div>
                                    <div class="car-price mt-3">
                                        <h4>$<?php echo number_format($car['price']); ?></h4>
                                    </div>
                                    <a href="car-details.php?id=<?php echo $car['id']; ?>" 
                                       class="btn btn-primary w-100 mt-3">View Details</a>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
                <nav aria-label="Page navigation" class="mt-4">
                    <ul class="pagination justify-content-center">
                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <li class="page-item <?php echo $page === $i ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?>">
                                    <?php echo $i; ?>
                                </a>
                            </li>
                        <?php endfor; ?>
                    </ul>
                </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
/* Mobile Sidebar */
.offcanvas {
    max-width: 300px;
}

@media (max-width: 991px) {
    .sidebar-filters .card {
        border: none;
        box-shadow: none;
    }
}

/* Sidebar Styles */
.brands-list a, 
.price-ranges a, 
.body-types a, 
.fuel-types a {
    color: #333;
    transition: all 0.3s ease;
    padding: 8px 12px;
    border-radius: 6px;
    display: block;
    text-decoration: none;
}

.brands-list a:hover {
    background-color: #f8f9fa;
    transform: translateX(5px);
}

/* Car Card Styles */
.car-card {
    border: 1px solid #eee;
    border-radius: 12px;
    overflow: hidden;
}

.car-card .card-body {
    padding: 1.25rem;
}

.car-info {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
    gap: 0.75rem;
    margin-bottom: 1rem;
}

.car-info span {
    display: flex;
    align-items: center;
    font-size: 0.875rem;
}

.car-title {
    font-size: 1.1rem;
    margin-bottom: 1rem;
    color: #333;
}

.car-price h4 {
    color: #28a745;
    font-weight: 600;
}

/* Animations */
.car-card {
    opacity: 0;
    animation: fadeInUp 0.5s ease forwards;
}

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* Add animation delay to cards */
<?php for ($i = 0; $i < 12; $i++): ?>
.row > div:nth-child(<?php echo $i + 1; ?>) .car-card {
    animation-delay: <?php echo $i * 0.1; ?>s;
}
<?php endfor; ?>

.btn-favorite {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 50%;
    width: 35px;
    height: 35px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;
}

.btn-favorite:hover {
    background: white;
    transform: scale(1.1);
}

.btn-favorite i {
    font-size: 1.2rem;
}
</style>

<script>
// Dynamic Models Loading
document.getElementById('brandSelect')?.addEventListener('change', function() {
    const modelSelect = document.getElementById('modelSelect');
    if (this.value) {
        fetch(`get_models.php?brand_id=${this.value}`)
            .then(response => response.json())
            .then(models => {
                modelSelect.innerHTML = '<option value="">Select Model</option>';
                models.forEach(model => {
                    const option = document.createElement('option');
                    option.value = model.id;
                    option.textContent = model.name;
                    modelSelect.appendChild(option);
                });
                modelSelect.disabled = false;
            });
    } else {
        modelSelect.innerHTML = '<option value="">Select Brand First</option>';
        modelSelect.disabled = true;
    }
});
</script>

<!-- Add this JavaScript code before the closing </body> tag -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle favorite toggle buttons
    document.querySelectorAll('.toggle-favorite').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const carId = this.getAttribute('data-car-id');
            const icon = this.querySelector('i');
            
            fetch('toggle_favorite.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'car_id=' + carId,
                credentials: 'same-origin'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Toggle the heart icon
                    icon.classList.toggle('far');
                    icon.classList.toggle('fas');
                    
                    // Show feedback to user
                    const toast = new bootstrap.Toast(document.createElement('div'));
                    toast.show();
                } else {
                    alert(data.message || 'Error updating favorite');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error updating favorite');
            });
        });
    });
});
</script>

<?php include 'includes/footer.php'; ?> 